package com.longrise.android.checkVersion;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.longrise.LEAP.Base.IO.JSONSerializer;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.IBaseListener;
import com.longrise.android.R;
import com.longrise.android.loaddata.newloaddata.LoadDataManager4;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.android.util.Util;
import com.longrise.android.widget.LButtonBg;
import com.longrise.android.widget.LLinearLayoutView;
import com.longrise.android.widget.OnRequestPremessionResultListener;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class UpdataAPK implements Callback, OnKeyListener
{
    private Context context = null;
    private Handler handler = null;
    private IBaseListener baseListener;//请求权限接口
    // APP名称
    private String appName = null;
    // 基础升级地址名称,用于请求接口
    private String baseurl = null;
    //下载基础APK地址
    private String downLoadBaseUrl;
    // 升级版本参数名称
    private String methodName = "lbcp_getAppVersion";
    //参数名称
    private String parameterName = "appname";
    // 回调接口
    private CheckVersionListener checkVersionListener;
    // 标识符,为0是为动检测版本,用在设置里面检测，有提示弹框
    private int mark = -1;
    private String _apkurl = "https://qcda.96520.com/LEAP/Download/default/2017/7/31/chezhutong.apk";
    private File _apkfile = null;
    private DownLoadManager _dm = null;
    private DownloadDialog bar;
    private Dialog _dialog2;
    private Dialog processDialog;
    private int currentVersion;

    public UpdataAPK(Context context, String appName, String baseurl,String downLoadBaseUrl, int currentVersion,IBaseListener baseListener)
    {
        this.context = context;
        this.appName = appName;
        this.baseurl = baseurl;
        this.downLoadBaseUrl = downLoadBaseUrl;
        this.currentVersion = currentVersion;
        this.baseListener = baseListener;

        handler = new Handler(this);
    }

    /**
     * 标识符,为0是为动检测版本,用在设置里面检测，有提示弹框
     * @param mark
     */
    public void setMark(int mark)
    {
        this.mark = mark;
    }

    /**
     * 检查版本接口名称，默认值为：lbcp_getAppVersion
     * @param methodname
     */
    public void setMethodName(String methodname)
    {
        this.methodName = methodname;
    }

    /**
     * 检查版本接口参数名称，默认值为：appname
     * @param parameterName
     */
    public void setParameterName(String parameterName)
    {
        this.parameterName = parameterName;
    }

    public void setCheckVersionListener(CheckVersionListener checkVersionListener)
    {
        this.checkVersionListener = checkVersionListener;
    }

    @Override
    public boolean handleMessage(Message message)
    {
        if (null == message)
        {
            return false;
        }
        switch (message.what)
        {
            case 100:
                Bundle bundle = message.getData();
                if (null == bundle)
                {
                    return false;
                }

                // "1"标识强制升级
                String upgrade = bundle.getString("upgrade");
                String apkurl = bundle.getString("apkurl");
                String remarks = bundle.getString("remarks");
                showDialog(upgrade, apkurl, remarks);

                break;
            case 101:
                if (null != checkVersionListener)
                {
                    checkVersionListener.onNoNewVersion();
                }
                break;
            case 102:
                Toast.makeText(context,"当前已是最新版本",Toast.LENGTH_SHORT).show();
                break;
            case 103:
                installApk();
                break;
            case 104:
                checkVersion();
                break;
        }
        return false;
    }

    private void showDialog(final String upgrade, final String apkUrl, String remarks)
    {
        if (null == context || null == upgrade || "".equals(upgrade) || null == apkUrl || "".equals(apkUrl)) {
            return;
        }

        // 自定义对话框
        final Dialog exitDialog = new Dialog(context, R.style.dialog_style);
        exitDialog.setCanceledOnTouchOutside(false);
        exitDialog.setCancelable(false);

        // ==================对话框布局==================
        int roundRadius = Util.dip2px(context, 10);
        LLinearLayoutView dialogBody = new LLinearLayoutView(context);
        dialogBody.setOrientation(LinearLayout.VERTICAL);
        dialogBody.setBackgroundColor(Color.parseColor("#287AC4"), Color.parseColor("#287AC4"),
                Color.parseColor("#287AC4"), Color.parseColor("#287AC4"), Color.parseColor("#287AC4"), roundRadius, 0,
                Color.parseColor("#287AC4"));

        // 标题
        int pad = Util.dip2px(context, 10);
        TextView setTitle = new TextView(context);
        setTitle.setGravity(Gravity.CENTER);
        setTitle.setText("版本更新");
        setTitle.setTextSize(17);
        setTitle.setTextColor(Color.WHITE);
        setTitle.setPadding(0, pad, 0, pad);
        dialogBody.addView(setTitle, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        // ------------主体-------------
        LLinearLayoutView bodyLayout = new LLinearLayoutView(context);
        bodyLayout.setGravity(Gravity.CENTER_HORIZONTAL);
        bodyLayout.setOrientation(LinearLayout.VERTICAL);
        bodyLayout.setBackgroundColor2(Color.WHITE, Color.WHITE, Color.WHITE, Color.WHITE, Color.WHITE,
                new float[]{0, 0, 0, 0, roundRadius, roundRadius, roundRadius, roundRadius}, 0,
                Color.parseColor("#55E0E0E0"));
        dialogBody.addView(bodyLayout, (int) (Util.getScreenWidth(context) * 0.7),
                LinearLayout.LayoutParams.WRAP_CONTENT);

        int padNoticeStr = Util.dip2px(context, 20);
        EditText editText = null;

        TextView noticeStr = new TextView(context);
        noticeStr.setPadding(0, padNoticeStr, 0, padNoticeStr);
        noticeStr.setBackgroundColor(Color.WHITE);
        noticeStr.setGravity(Gravity.CENTER);
        noticeStr.setText("有新版本，请及时更新。");
        noticeStr.setTextSize(17);
        noticeStr.setTextColor(Color.parseColor("#AA000000"));
        LinearLayout.LayoutParams noticeStrLP = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        noticeStrLP.weight = 1;
        bodyLayout.addView(noticeStr, noticeStrLP);

        // 分隔线
        View line = new View(context);
        line.setBackgroundColor(Color.parseColor("#E0E0E0"));
        bodyLayout.addView(line, LayoutParams.MATCH_PARENT, 1);

        LinearLayout btnLayout = new LinearLayout(context);
        bodyLayout.addView(btnLayout, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

        float[] myRoundRadius = null;
        if ("1".equals(upgrade))
        {
            // 強制更新，隐藏取消按钮
            myRoundRadius = new float[]{0, 0, 0, 0, roundRadius, roundRadius, roundRadius, roundRadius};
        }
        else
        {
            myRoundRadius = new float[]{0, 0, 0, 0, roundRadius, roundRadius, 0, 0};

            // 选择安装，不隐藏取消按钮
            LButtonBg cancelBtn = new LButtonBg(context);
            cancelBtn.setBackgroundColor2(Color.WHITE, Color.parseColor("#E0E0E0"), Color.parseColor("#E0E0E0"), -10,
                    Color.parseColor("#E0E0E0"), new float[]{0, 0, 0, 0, 0, 0, roundRadius, roundRadius}, 0,
                    Color.parseColor("#E0E0E0"));
            cancelBtn.setText("取消");
            cancelBtn.setTextColor(Color.parseColor("#AA000000"));
            cancelBtn.setTextSize(15);
            LinearLayout.LayoutParams cancelLP = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    Util.dip2px(context, 45));
            btnLayout.addView(cancelBtn, cancelLP);
            cancelLP.weight = 1;

            cancelBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View view)
                {
                    exitDialog.cancel();
                    if (null != handler)
                    {
                        handler.sendEmptyMessage(101);
                    }
                }
            });

            // 分隔线
            View line2 = new View(context);
            line2.setBackgroundColor(Color.parseColor("#E0E0E0"));
            btnLayout.addView(line2, 1, LayoutParams.MATCH_PARENT);
        }
        // 确定按钮
        LButtonBg setOK = new LButtonBg(context);
        setOK.setBackgroundColor2(Color.WHITE, Color.parseColor("#E0E0E0"), Color.parseColor("#E0E0E0"), -10,
                Color.parseColor("#E0E0E0"), myRoundRadius, 0, Color.parseColor("#E0E0E0"));
        setOK.setText("确定");
        setOK.setTextColor(Color.parseColor("#AA000000"));
        setOK.setTextSize(15);
        LinearLayout.LayoutParams setOKLP = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                Util.dip2px(context, 45));
        setOKLP.weight = 1;
        btnLayout.addView(setOK, setOKLP);
        setOK.setTag(editText);
        setOK.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                if(!"1".equals(upgrade))
                {
                    exitDialog.cancel();
                }
                showdownloadDialog();
                Thread thread = new Thread(null, _doDownLoadApk, "downloadapkBackground");
                thread.start();

            }
        });
        exitDialog.setContentView(dialogBody);
        exitDialog.show();
    }

    private void showdownloadDialog()
    {
        if (null == context) {
            return;
        }
        View view = View.inflate(context, R.layout.checkversion_download_dialog_layout, null);
        bar = (DownloadDialog) view.findViewById(R.id.download_dialog);
        _dialog2 = new Dialog(context, R.style.dialog_style);
        _dialog2.setCancelable(false);
        _dialog2.setCanceledOnTouchOutside(false);
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        _dialog2.setContentView(view, lp);
        _dialog2.show();
    }

    /**
     * 检查版本更新
     */
    public void checkVersion()
    {
        if(baseListener == null)
        {
            if (null != handler)
            {
                handler.sendEmptyMessage(101);
            }
            return;
        }
        //请求权限
        if(baseListener instanceof IBaseListener)
        {
            ((IBaseListener)baseListener).requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, null, new OnRequestPremessionResultListener() {
                @Override
                public void onAllowPremession()
                {
                    startCheckVersion();
                }

                @Override
                public void onDissAllowPremession()
                {
                    ((IBaseListener)baseListener).showNOPresessionDialog(-1);
                }
            });
        }
    }

    /**
     * 开始检测
     */
    private void startCheckVersion()
    {
        try
        {
            if (null == context || null == appName || appName.isEmpty() || null == baseurl || baseurl.isEmpty())
            {
                if (null != handler)
                {
                    handler.sendEmptyMessage(101);
                }
                return;
            }


            EntityBean bean = new EntityBean();
            bean.set(parameterName, appName);
            LoadDataManager4.getInstance(context).setUpdateRequest(true);
            LoadDataManager4.getInstance(context).callService(null, baseurl, methodName, bean,
                    new LoadDataManagerFather.OnRequestCompleteListener()
                    {
                        @Override
                        public void onSuccess(String key, String service, Object result)
                        {
                            EntityBean _checkVersion_eb = (EntityBean) JSONSerializer.getInstance().DeSerialize((String) result , EntityBean.class);
                            if (_checkVersion_eb == null)
                            {
                                if (null != handler)
                                {
                                    handler.sendEmptyMessage(101);
                                }
                                return;
                            }

                            String appversion = _checkVersion_eb.getString("appversion");
                            if (null == appversion || "".equals(appversion))
                            {
                                if (null != handler)
                                {
                                    handler.sendEmptyMessage(101);
                                }
                                return;
                            }

                            int iappv = Integer.parseInt(appversion);
                            if (iappv > currentVersion)
                            {

                                // 版本描述
                                String remarks = _checkVersion_eb.getString("remarks", "");
                                // 是否强制更新标示符
                                String upgrade = _checkVersion_eb.getString("upgrade", "0");
                                //PrefUtils.setString(context,"remarks",remarks);//强制更新后要存版本的更新描述，首页弹框用
                                // cdn完整路径
                               /* _apkurl = _checkVersion_eb.getString("cdnpath");
                                if (_apkurl == null || "".equals(_apkurl)) {
                                    String[] apk_path = (String[]) _checkVersion_eb.get("apk", null);

                                    if (null == apk_path || "".equals(apk_path)) {
                                        if (null != handler) {
                                            handler.sendEmptyMessage(101);
                                        }
                                        return;
                                    }
                                    String string = apk_path[0];
                                    if (null != string && !"".equals(string)) {
                                        // APK 完整的下载路径
                                        _apkurl = downLoadBaseUrl + string;
                                    }
                                }*/

                                if (null != handler)
                                {
                                    Message message = new Message();
                                    Bundle bundle = new Bundle();
                                    bundle.putString("remarks", remarks);
                                    bundle.putString("upgrade", upgrade);
                                    bundle.putString("apkurl", _apkurl);
                                    message.setData(bundle);
                                    message.what = 100;
                                    handler.sendMessage(message);
                                }
                            }
                            else
                            {
                                if(mark == 0)
                                {
                                    if (null != handler)
                                    {
                                        handler.sendEmptyMessage(102);
                                    }
                                }
                            }
                        }

                        @Override
                        public void onError(String key, String service, LoadDataManagerFather.ResultType resultType)
                        {
                            if (null != handler)
                            {
                                handler.sendEmptyMessage(101);
                            }
                        }

                        @Override
                        public void onFinished(String key, String service)
                        {

                        }
                    });

        }
        catch (Exception ex)
        {
            if (null != handler)
            {
                handler.sendEmptyMessage(101);
            }
        }
    }

    public interface CheckVersionListener
    {
        void onNoNewVersion();
    }

    // APK下载类
    class DownLoadManager
    {
        private boolean isbreak = false;

        public DownLoadManager()
        {
        }

        public File getFileFromServer(String path, ProgressBar pd) throws Exception {
            if (null == path)
                return null;

            // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                return null;
            }
            try {
                HttpURLConnection conn = null;
                URL url = new URL(path);
                if (null != url) {
                    conn = (HttpURLConnection) url.openConnection();
                    if (null != conn) {
                        conn.setConnectTimeout(5000);
                        if (200 == conn.getResponseCode()) {
                            this.isbreak = false;
                            // 获取到文件的大小
                            if (null != pd) {
                                pd.setMax(conn.getContentLength());
                            }
                            InputStream is = conn.getInputStream();
                            String locDir = appName;
                            if (null == locDir)
                            {
                                locDir = "co";
                            }
                            String updateApk = appName + ".apk";
                            File file = new File(context.getExternalCacheDir(), locDir);
                            if (null != file) {
                                if (!file.exists()) {
                                    file.mkdir();
                                }
                            }
                            file = new File(context.getExternalCacheDir(), locDir + "/" + updateApk);
                            if (null != file) {
                                if (file.exists()) {
                                    file.delete();
                                }
                                FileOutputStream fos = new FileOutputStream(file);
                                BufferedInputStream bis = new BufferedInputStream(is);
                                byte[] buffer = new byte[1024];
                                int len;
                                int total = 0;
                                while ((len = bis.read(buffer)) != -1) {
                                    if (isbreak) {
                                        file = null;
                                        break;
                                    }
                                    fos.write(buffer, 0, len);
                                    total += len;
                                    if (null != pd) {
                                        pd.setProgress(total);
                                    }
                                }
                                fos.close();
                                bis.close();
                                is.close();
                            }

                            return file;
                        }
                    }
                }

            } catch (Exception ex) {
            }
            return null;

        }

        public void stop() {
            this.isbreak = true;
        }
    }

    // 下载数据
    private Runnable _doDownLoadApk = new Runnable() {
        @Override
        public void run() {
            try
            {
                _apkfile = null;
                if (null != _apkurl && !"".equals(_apkurl))
                {
                    if (null == _dm)
                    {
                        _dm = new DownLoadManager();
                    }
                    _apkfile = _dm.getFileFromServer(_apkurl, bar);
                    if (null != handler && null !=_apkfile)
                    {
                        handler.sendEmptyMessage(103);
                    }
                    else
                    {
                        if (null != handler)
                        {
                            handler.sendEmptyMessage(101);
                        }
                        Toast.makeText(context,"下载失败，请重新启动应用并保证网络通畅",Toast.LENGTH_SHORT).show();
                    }
                }
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
                if (null != handler)
                {
                    handler.sendEmptyMessage(101);
                }
            }
        }
    };


    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (null != this._dialog2 && this._dialog2.isShowing())
            {
                _dm.stop();
                this._dialog2.dismiss();
            }
        }
        return false;
    }

    /**
     * 按照APK
     */
    private void installApk()
    {
        if (Build.VERSION.SDK_INT >= 24)
        {
            //判断版本android7.0

            Uri apkUri = FileProvider.getUriForFile(context, "com.longrise.co.update.fileprovider", _apkfile);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            context.startActivity(intent);
        }
        else
        {
            //android 7.0以下

            Intent intent = new Intent();
            // 执行动作

            intent.setAction(Intent.ACTION_VIEW);
            // 执行的数据类型

            intent.setDataAndType(Uri.fromFile(this._apkfile), "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 执行打开文件

            context.startActivity(intent);
        }



        _dialog2.dismiss();
    }
}
